from etgui import *
from PyDialog import PyDialog
import CmdNo,sys,string
class ErrorDialog(PyDialog):
	text=''
	def __init__(self):
		self.item=MultilineTextItem("")
		self.scr=Scroller(self.item)
	def write(self,str):
		self.text=self.text+str
		self.SetString()
	def ShowUnderMouse(self):
		self.impl.ShowUnderMouse()
	def MakeContent(self):
		return VExpander(
			items=(
				self.scr,
				Separator(),
				AlignBox(eVObjHExpand,
					flags=eVObjVFixed,
					inner=HBox( 
						align=eVObjVExpand|eVObjHExpand|eVObjHCenter,
						items= (
							ActionButton("Clear",action=self.Clear),
							ActionButton(CmdNo.cIdCancel,"Done",default=1)
						)
					)
				)
			)
		)
	def Clear(self):
		self.text=""
		self.SetString()
	def SetString(self):
		self.item.SetString(self.text)
class ErrorDialogFile:
	def __init__(self):
		dialog=ErrorDialog()
		dialog.impl=MakeDialog(dialog)
		self.__data=''
		self.__dialog=dialog
	def write(self,data):
		self.__data=self.__data+data
		if '\n' in data:
			#stderr.write(self.__data)
			self.__dialog.write(self.__data)
			self.__dialog.ShowUnderMouse()
			self.__data=''
class ErrorLogFile:
	def __init__(self,location='python'):
		self.__data=''
		self.__location=location
	def write(self,data):
		self.__data=self.__data+data
		if '\n' in data:
			ETWarning(self.__location,self.__data)
			self.__data=''
class IgnoreFile:
	def write(self,data):
		pass

stdout=sys.stdout
stderr=sys.stderr
def Init():
	SetError(EnvGetString("Python.Errors","log"))
def SetError(what):
	#stdout.write("%s\n"%what)
	what=string.strip(string.lower(what))
	if what=='log':
		sys.stderr=ErrorLogFile('stderr')
		sys.stdout=ErrorLogFile('stdout')
	elif what=='dialog':
		sys.stdout=ErrorDialogFile()
		sys.stderr=stderr
		sys.stderr=sys.stdout
	elif what in ('ignore',''):
		sys.stdout=sys.stderr=IgnoreFile()
	elif what=='std':
		sys.stdout=stdout
		sys.stderr=stderr
	else:
		ETError("Preferences",'"Python.Errors" value must be "log", "dialog", "ignore" or "std"')
		
Init()
